package com.jmp.livepush;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.live.v20180801.LiveClient;
import com.tencentcloudapi.live.v20180801.models.ForbidLiveStreamRequest;
import com.tencentcloudapi.live.v20180801.models.ForbidLiveStreamResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LivePushClientImpl implements LivePushClient {
    private static String key = "ceb3300e13b45ee5a0bcc5a5058f71ee";
    private static String pushUrl = "rtmp://live.push.hongmushichang.com/live/";
    private static String pullUrl = "http://live.pull.hongmushichang.com/live/";
    private static String videoSuffix = ".flv";

    private PushUrlGenerator pushUrlGenerator = new PushUrlGenerator();

    private LiveClient client;

    public LivePushClientImpl() {
        Credential cred = new Credential("AKIDSggQyQFxwhHbu5vqgOwMchdO2E0AjsHS", "FYcT4VDvSkrlT4VggbP3UmslT4XZMxJU");

        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("live.tencentcloudapi.com");

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        client = new LiveClient(cred, "", clientProfile);
    }

    @Override
    public String getPushUrl(String streamName, long txTime) {
        return pushUrl + streamName + "?" + pushUrlGenerator.getPushUrl(key, streamName, txTime);
    }

    @Override
    public String getPullUrl(String streamName) {
        return pullUrl + streamName + videoSuffix;
    }

    @Override
    public void forbidLiveStream(String streamName) {
        String params = "{\"AppName\":\"live\",\"DomainName\":\"live.push.hongmushichang.com\",\"StreamName\":\"" + streamName + "\"}";
        ForbidLiveStreamRequest req = ForbidLiveStreamRequest.fromJsonString(params, ForbidLiveStreamRequest.class);

        ForbidLiveStreamResponse resp;
        try {
            resp = client.ForbidLiveStream(req);
            log.info("return: {}", ForbidLiveStreamRequest.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.error(e.getMessage(), e);
        }
    }
}
